package com.sxj.web.servlet;

import com.sxj.web.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Arrays;

/**
 * @author 石小俊
 * @date 2024年03月01日 18:36
 */
@WebServlet("/modifyEmp")
public class ModifyEmpServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String salary = request.getParameter("salary");
        String gender = request.getParameter("gender");
        String edu = request.getParameter("edu");
        String[] hobbies = request.getParameterValues("hobbies");
        System.out.println("name:" + name + ",salary:" + salary + ",gender:" + gender + ",edu:" + edu + ",hobbies:" + Arrays.toString(hobbies));

        String url = "jdbc:mysql://127.0.0.1:3306/ems?useUnicode=true&characterEncoding=utf-8";
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, "root", "");
            String sql = new StringBuffer()
                    .append(" update t_emp ")
                    .append(" set ")
                    .append("   name = ?, ")
                    .append("   salary = ?, ")
                    .append("   gender = ?, ")
                    .append("   edu = ?, ")
                    .append("   hobbies = ? ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1, name);
            ps.setDouble(2, Double.parseDouble(salary));
            ps.setString(3, gender);
            ps.setString(4, edu);
            ps.setString(5, StringUtil.arrayToString(hobbies));
            ps.setInt(6, Integer.parseInt(id));
            ps.executeUpdate();
            response.sendRedirect(request.getContextPath()+"/findAll");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
